import axios from 'axios'
import qs from 'qs'
import store from '@/store';
import router from '@/router';
import config from "./config";
const env = process.env.VUE_APP_DOMAIN_CONFIG;
const fetch = axios.create({
    timeout: 60000,
    baseURL:env=='dev'?'/App':config.http,
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
    }
  })
  fetch.interceptors.request.use((config) => {
    let requestData={
        ...config.data
    }
    if(store.state.token){
        requestData.token = store.state.token;
    }
    //在发送请求之前做某件事
    if (config.method === "post") {
        config.data=qs.stringify(requestData);
    }else{
        config.params = qs.parse(requestData);
    }
    return config;
},(error) =>{
    console.log("错误的传参", 'fail');
    return Promise.reject(error);
});

fetch.interceptors.response.use((res) =>{
    //对响应数据做些事
    if(res.data.code == '100'){
      router.push('/login')
    }else{
        return res.data;
    }

}, (error) => {
    console.log("网络异常", 'fail');
    return Promise.reject(error);
});

//上传图片
const service = axios.create({
  timeout: 60000,
  baseURL:env=='dev'?'/App':config.http,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
  }
})

service.interceptors.request.use((config) => {

  return config;
},(error) =>{
  console.log("错误的传参", 'fail');
  return Promise.reject(error);
});

service.interceptors.response.use((res) =>{
  //对响应数据做些事
  if(res.data.code == '403'){
      window.location.href = '/phonelogin'
  }else{
      return res.data;
  }

}, (error) => {
  console.log("网络异常", 'fail');
  return Promise.reject(error);
});

const http={
    get:(url,data,config={})=>{
      return fetch({
        method: 'get',
        url,
        data,
  
      })
    },
    post:(url,data,config={})=>{
      return fetch({
        method: 'post',
        url,
        data,
      })
    },
    postup(url, data, headers) {
      return service.post(url, data, headers)
    },
    all:axios.all
  
  }
export default {
    install: function(Vue, Option) {
        Object.defineProperty(Vue.prototype, "$http", { value: http });
    }
};





